package cn.Y_Qiu.user.service.impl;

import cn.Y_Qiu.basic.exception.BusinessException;
import cn.Y_Qiu.basic.util.MessageUtil;
import cn.Y_Qiu.basic.util.StrUtils;
import cn.Y_Qiu.user.domain.User;
import cn.Y_Qiu.user.mapper.UserMapper;
import cn.Y_Qiu.user.service.IVerifycodeService;
import cn.Y_Qiu.user.util.UserCodeutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl  implements IVerifycodeService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void checkverifycode(Map<String,String> params) {
        //1.校验
        //1.1 手机号不能为空
        //1.2 手机号是否被注册 查询t_user表
        // 获取phone和type
        String phone = params.get("phone");
        String type = params.get("type");
        String businesskey = "";
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)){
            throw new BusinessException("参数为空");
        }
        if ("register".equals(type)){
            // 注册短信逻辑
            User user = userMapper.queryByPhone(phone);
            if (user != null){
                throw new BusinessException("手机已注册");
            }
            businesskey = UserCodeutil.BUSINESS_REGISTER_PREFIX +phone;
        } else if ("binder".equals(type)){
            businesskey = UserCodeutil.BUSINESS_BINDER_PREFIX + phone;
        }
        if(StringUtils.hasLength(businesskey)){
            sendverifycode(businesskey, phone);
        }

    }

    @Override
    public void sendverifycode(String businesskey, String  phone) {
        //2.判断验证码是否有效（3分钟），从redis中是否能拿到 key： business_register:15982495855
        Object value = redisTemplate.opsForValue().get(businesskey);
        // 外部定义验证码空串提高效率
        String code = "";
        //2.1.1 如果没有过重发时间,报错：请勿重发获取验证码  1*60*1000
        if (value != null){
            // 获取验证码生成的时间戳
            String timetemp = value.toString().split(":")[1];
            //2.1 如果拿到了 需要判断是否过了1分钟重发时间
            if (System.currentTimeMillis() - Long.valueOf(timetemp) <= 1 * 60 * 1000){
                throw new BusinessException("请稍后再发送验证码");

            } else {
                //2.1.2 如果过了，使用上次的验证码====
                code = value.toString().split(":")[0];
            }
            // 如果数据库里没有验证码，则生成新的验证码
        } else {
            //2.2.1 直接生成新的验证码  ===
            code = StrUtils.getComplexRandomString(4);
        }
        //3.存储redis 设置3分钟过期
        redisTemplate.opsForValue().set(businesskey, code + ":" +  System.currentTimeMillis(),3, TimeUnit.MINUTES);
        //4.发送短信通知客人 验证码是：9527 请在3分钟内使用
        System.out.println("发送" + code);
        //EmailUtil.sendemail(, , );
        MessageUtil.send(phone, "验证码是:" + code);

    }

}
